package com.working.libcommon.exts

import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.working.libcommon.util.SupplementJsonAdapterFactory
import java.lang.reflect.Type


object MoshiHolder {
    val instance: Moshi =
        Moshi.Builder().add(KotlinJsonAdapterFactory()).add(SupplementJsonAdapterFactory()).build()
}

fun <T> T.toJson(type: Class<T>, vararg typeArguments: Type): String {
    if (typeArguments.isNullOrEmpty()) {
        return MoshiHolder.instance.adapter(type).toJson(this)
    }
    val realType = Types.newParameterizedType(type, *typeArguments)
    return MoshiHolder.instance.adapter<T>(realType).toJson(this)
}

fun <T> T.toJson(type: Type): String {
    return MoshiHolder.instance.adapter<T>(type).toJson(this)
}

fun <T> String.parseJson(type: Class<T>): T? {
    return MoshiHolder.instance.adapter(type).fromJson(this)
}

fun <T> String.parseJson(typeOfT: Type): T? {
    return MoshiHolder.instance.adapter<T>(typeOfT).fromJson(this)
}